# -*- coding: utf-8 -*-

import datetime
import time

from debug import debug

class StatsAggregator:
    ''' Aggregates informations about the log file, and notifies the notifier
    (sic...)'''

    def __init__(self, notifier):
        self.n = notifier
        self.d = {  'keycount': {}
                  , 'last_process_event': {}
                  , 'processes': {}
                  , 'websites': {}
                  , 'sum': { 'keycount': 0, 'processes': 0, 'websites': 0 }
                  , 'keysum_history': []
                  , 'keysum_counter': 0
                  , 'achievements': []
                 }
        debug('Notifier OK')
        return

    def on_process_event(self, e):
        self.update_keycount(e['keycount'])
        self.update_processes(e['process'])
        self.update_websites(e['website'])

        if self.d['last_process_event']:
            delta = self.compute_timediff(self.d['last_process_event'], e)
            self.add_focus_time(self.d['processes'], e['process'], delta)
            if e['website']:
                self.add_focus_time(self.d['websites'], e['website'], delta)
            if delta > 0:
                self.update_keysum_history(self.d['last_process_event'])

        self.n.on_stats_update(e, self.d)

        self.d['last_process_event'] = e

        return

    def update_keycount(self, keystrokes):
        '''Keeps the keycount variable up to date with the total character
        count'''
       # debug('Keystrokes:')
       # for i in self.d['keycount']['count'].keys():
       #     debug(i + ': ' + str(self.d['keycount']['ratio'][i]))
        for i in keystrokes: #keystrokes is a list of characters
            try:
                self.d['keycount'][i]['count'] += 1
            except KeyError:
                self.d['keycount'][i] = {}
                self.d['keycount'][i]['count'] = 1
            self.d['keysum_counter'] += 1
            self.d['sum']['keycount'] += 1

        for i in self.d['keycount'].keys():
            self.d['keycount'][i]['ratio'] = (
                float(self.d['keycount'][i]['count']) /
                self.d['sum']['keycount'])
        return

    def update_processes(self, process_name):
        '''Keeps track of process occurence and ratio'''
        try:
            self.d['processes'][process_name]['count'] += 1
        except KeyError:
            self.d['processes'][process_name] = {}
            self.d['processes'][process_name]['count'] = 1
        self.d['sum']['processes'] += 1

        for p in self.d['processes'].keys():
            self.d['processes'][p]['ratio'] = (
                float(self.d['processes'][p]['count']) /
                self.d['sum']['processes'])
        return

    def update_websites(self, website):
        '''Keeps track of webpage occurence and ratio'''
        if website:
            try:
                self.d['websites'][website]['count'] += 1
            except KeyError:
                self.d['websites'][website] = {}
                self.d['websites'][website]['count'] = 1
            self.d['sum']['websites'] += 1

            for w in self.d['websites'].keys():
                self.d['websites'][w]['ratio'] = (
                    float(self.d['websites'][w]['count']) /
                    self.d['sum']['websites'])
        return

    def compute_timediff(self, last, e):
        '''Compute the time spent in last application focus in minutes'''
        last_time_s = (last['year'] + ' ' + last['month'] + ' ' + last['day'] +
                     ' ' + last['hour'] + ' ' + last['minute'])
        last_time = datetime.datetime.strptime(last_time_s, '%Y %m %d %H %M')

        new_time_s = (e['year'] + ' ' + e['month'] + ' ' + e['day'] +
                     ' ' + e['hour'] + ' ' + e['minute'])
        new_time = datetime.datetime.strptime(new_time_s, '%Y %m %d %H %M')

        delta_time = new_time - last_time

        return (delta_time.seconds / 60)

    def add_focus_time(self, dic, key, t):
        try:
            dic[key]['focus_time'] += t
        except KeyError:
            dic[key]['focus_time'] = t

    def update_keysum_history(self, last):
        last_time = (last['year'] + ' ' + last['month'] + ' ' + last['day'] +
                     ' ' + last['hour'] + ' ' + last['minute'])
        if self.d['keysum_counter'] > 0:
            self.d['keysum_history'].append((last_time,
                                            self.d['keysum_counter']))
        self.d['keysum_counter'] = 0
